package DFS;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 求解两个指定节点之间的路径问题
 */
public class Path {
    private Graph graph;
    private int src;
    private int dst;
    private int[] pre;
    private boolean[] visited;

    public Path(Graph graph, int s, int t) {
        this.graph = graph;
        graph.validateVertex(s);
        graph.validateVertex(t);
        this.src = s;
        this.dst = t;
        this.visited = new boolean[graph.getVertexNum()];
        this.pre = new int[graph.getVertexNum()];
        for (int i = 0; i < this.pre.length; i++) {
            this.pre[i] = -1;
        }
        dfs(s, s);
        for (boolean e:this.visited){
            System.out.print(e+", ");
        }
        System.out.println();
    }

    private boolean dfs(int v, int parent) {
        this.visited[v] = true;
        this.pre[v] = parent;
        if (v == this.dst) {
            return true;
        }
        for (int w : graph.adj(v)) {
            if (!this.visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isConnectedTo() {
        return visited[this.dst];
    }

    public Iterable<Integer> path() {
        List<Integer> res = new ArrayList<>();
        if (!isConnectedTo()) {
            return res;
        }
        int cur = this.dst;
        while (cur != src) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(src);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] a) {
        Graph graph = new Graph("gDfs.txt");
        Path paath = new Path(graph, 0,6);
        System.out.println("0 -> 6 : " + paath.path());
    }
}
